package com.example.wallet.db

import com.example.shushiyunsst.fragment.main.constant.CURRENT_ACCOUNT_KEY
import com.example.shushiyunsst.fragment.main.constant.CURRENT_SIGNED_UP_KEY
import com.example.wallet.bean.UserInfoWrapper
import com.example.wallet.utils.Preference
import com.example.wallet.utils.UserInfoTempleHolder

class UserInfoManager private constructor() {

    companion object {

        val userInfoManager by lazy { UserInfoManager() }

    }

    private var mWrapper: UserInfoWrapper? = null

    fun getUserInfoWrapper(): UserInfoWrapper? {

        val currentSignedUpKey = Preference.HOLDER.getCustomAppProfile(CURRENT_SIGNED_UP_KEY)

        if (mWrapper != null
            || currentSignedUpKey.isNullOrEmpty()
        ) return mWrapper

        val userInfoDao = AccountDatabase.getInstance().getUserInfoDao()

        mWrapper = userInfoDao.getCache(currentSignedUpKey)

        return mWrapper
    }

    fun haveSignedIn(): Boolean {
        return getUserInfoWrapper() != null
    }

    fun saveUserInfoWrapper(newWrapper: UserInfoWrapper?){

        Preference.HOLDER.addCustomAppProfile(CURRENT_SIGNED_UP_KEY,newWrapper?.token)

        mWrapper=newWrapper

        val userInfoDao = AccountDatabase.getInstance().getUserInfoDao()

        userInfoDao.save(newWrapper)

        UserInfoTempleHolder.upDataUserInfoTemple()
    }

    fun signOutUserInfoWrapper(){

        Preference.HOLDER.removeCustomAppProfile(CURRENT_SIGNED_UP_KEY)

        val userInfoDao = AccountDatabase.getInstance().getUserInfoDao()

        userInfoDao.delete(mWrapper)

        mWrapper=null
    }

}